package classes
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;

	public class QbtHandler extends EventDispatcher
	{	
		private static var instance:QbtHandler;
		private var _lastResult:ArrayCollection;
		private var _relatedTags:ArrayCollection;
		
		[Bindable ("qbtResult")]
		public function get lastResult():ArrayCollection{
			return _lastResult;
		}
		[Bindable ("qbtResult")]
		public function get relatedTags():ArrayCollection{
			return _relatedTags;
		}
		public function QbtHandler(target:IEventDispatcher=null){
			super(target);
		}
		
		public function performQBT(theTags:String):void{
			dispatchEvent(new ResultEvent("performingQbt",false,true,theTags.toString()));
			var servletReq:HTTPService = new HTTPService();
			servletReq.method = "GET";
			servletReq.url = Settings.getInstance().qbtServletURL;
			servletReq.addEventListener(ResultEvent.RESULT, qbtResultHandler);
			servletReq.send({tags: theTags});
		}
		
		private function qbtResultHandler(event:ResultEvent):void{
			_lastResult = Parser.parseServletResult(event); 
			_relatedTags = Parser.parseQbtRelatedTags(event);
			if(_lastResult == null || _relatedTags == null){
				dispatchEvent(new Event("qbtError"));
			}else{
				dispatchEvent(new ResultEvent("qbtResult",false,true,lastResult));
			}
		}
		
		public static function getInstance():QbtHandler{
			if(instance==null)
				instance = new QbtHandler();
			return instance;
		}
	}
}